package com.z.config;

import java.io.File;
import java.util.Calendar;
import java.util.Date;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;

public class ConfigReader {
	private static ConfigReader configReader;
	public static ConfigReader getInstance(){
		if(configReader==null){
			configReader=new ConfigReader();
		}
		return configReader;
	}
	
	// 文件路径
    private static final String CONFIG_FILE="app.properties";
    // 数据库文件路径配置名称
    private static final String CONFIG_ITEM_DB_PATH="db_path";
    // 附件文件存贮目录
    private static final String CONFIG_ITEM_ATTACH_ROOT="attachment_root";
    
    
    private static final String DEFAULT_DB_PATH="db.dat";
    private static final String DEFAULT_ATTATCH_ROOT="attach/";
    /**
     * 获取配置的数据库文件路径
     * @return
     */
    public String getDbPath(){
    	try {
			Configuration config = new PropertiesConfiguration(CONFIG_FILE);
			String path = config.getString(CONFIG_ITEM_DB_PATH);
			if(path==null||path.trim().length()==0){
				return DEFAULT_DB_PATH;
			}
			return path;
		} catch (ConfigurationException e) {
		}
    	return DEFAULT_DB_PATH;
    }
    /**
     * 获取配置的附件存贮根目录
     * @return
     */
    public String getAttachRoot(){
    	try {
			Configuration config = new PropertiesConfiguration(CONFIG_FILE);
			String path = config.getString(CONFIG_ITEM_ATTACH_ROOT);
			if(path==null||path.trim().length()==0){
				return DEFAULT_ATTATCH_ROOT;
			}
			if(!path.endsWith("/")){
				path+="/";
			}
			return path;
		} catch (ConfigurationException e) {
		}
    	return DEFAULT_ATTATCH_ROOT;
    }
    

	/**
	 * 构建存储目录
	 * @param name
	 * @return
	 */
	public String makeFolder(String name){
		Date now = new Date(System.currentTimeMillis());
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(now);
		String root = getAttachRoot();
		if(!root.endsWith("/")){
			root+="/";
		}
		String year = String.valueOf(calendar.get(Calendar.YEAR));
		String month = String.valueOf(calendar.get(Calendar.MONTH));

		String path = year + "/" + month + "/";
		if(name!=null&&name.length()>0){
			path=name+"/"+path;
		}
		File folder = new File(root + path);
		if (!folder.exists()) {
			folder.mkdirs();
		}
		return root + path;
	}
	
	public String removeRoot(String path){
		String root = getAttachRoot();
		return path.replace(root, "");
	}
}
